﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Text;
using Rss;
using WorkItemRSS.Properties;

namespace WorkItemRSS
{
    /// <summary>
    /// 
    /// </summary>
    public class Feed
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="Feed"/> class.
        /// </summary>
        public Feed()
        {

        }

        /// <summary>
        /// Gets the feed.
        /// </summary>
        /// <param name="UserHostAddress">The user host address.</param>
        /// <param name="AssignedTo">The assigned to.</param>
        /// <param name="WorkItemType">Type of the work item.</param>
        /// <returns></returns>
        public DataSet GetFeed(string UserHostAddress, string AssignedTo, string WorkItemType, string tfsProjectName)
        {
            try
            {
                DAL oDAL = new DAL();
                return oDAL.GetFeed(UserHostAddress, AssignedTo, WorkItemType, tfsProjectName);
            }
            catch
            {
                return null;
            }
        }

        /// <summary>
        /// no new feeds found
        /// </summary>
        /// <param name="context">The context. object that provides references to the intrinsic server objects (for example, Request, Response, Session, and Server) used to service HTTP requests.</param>
        public string NoFeeds(string ChannelName, string tfsProjectName)
        {
            StringBuilder spXML = new StringBuilder();
            spXML.AppendLine("<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>");
            spXML.AppendLine("<rss version=\"2.0\">");
            spXML.AppendLine("<channel>");
            spXML.Append("<title>");
            spXML.Append("TFS-");
            spXML.Append(tfsProjectName);
            spXML.Append("-");
            spXML.Append(ChannelName);
            spXML.AppendLine("</title>");
            spXML.Append("<description>work items for ");
            spXML.Append(tfsProjectName);
            spXML.AppendLine("</description>");
            spXML.Append("<link>");
            spXML.Append(new System.Uri(HttpContext.Current.Request.Url.AbsoluteUri));
            spXML.AppendLine("</link>");
            spXML.AppendLine("<language>en</language>");
            spXML.AppendLine("<copyright>Copyright © 2011, LinkDev</copyright>");
            spXML.AppendLine("<managingEditor>taha.amin@mail.link.net</managingEditor>");
            spXML.Append("<pubDate>");
            spXML.Append(DateTime.Now);
            spXML.AppendLine("</pubDate>");
            spXML.AppendLine("<docs>http://backend.userland.com/rss</docs>");
            spXML.AppendLine("<generator>Taha Amin</generator>");
            spXML.AppendLine("<ttl>0</ttl>");
            spXML.AppendLine("</channel>");
            spXML.AppendLine("</rss>");
            return spXML.ToString();
        }
        /// <summary>
        /// Generate the RSS Feed by fetching the values from Database
        /// </summary>
        public void CreateRssFeed(out RssFeed rssFeed, string UserHostAddress, string AssignedTo, string WorkItemType, string tfsProjectName, string ChannelName)
        {
            rssFeed = new RssFeed();
            rssFeed.Encoding = Encoding.UTF8;
            DataSet ds = GetFeed(UserHostAddress, AssignedTo, WorkItemType, tfsProjectName);
            if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                // Fill in our channel information:
                RssChannel channel = new RssChannel();
                channel.Title = "TFS-" + tfsProjectName + ChannelName;

                System.Uri uri = new System.Uri(HttpContext.Current.Request.Url.AbsoluteUri);
                channel.Link = uri;
                channel.Description = "work items for " + tfsProjectName + "-WorkItem";
                channel.Generator = "Taha Amin";
                channel.Language = "en";
                channel.Copyright = "Copyright © " + System.DateTime.Now.Year + ", LinkDev";
                channel.ManagingEditor = "taha.amin@mail.link.net";
                channel.TimeToLive = 0;
                channel.PubDate = System.DateTime.Now;
                // Add items.
                RssItem item;
                RssGuid rssGuid;
                RssSource rssSource;
                foreach (DataRow drow in ds.Tables[0].Rows)
                {
                    item = new RssItem();
                    item.Title = "WorkItemID:" + drow["ID"].ToString() + "-" + drow["Title"].ToString() + " [State:" + drow["State"].ToString() + "]";
                    if (!string.IsNullOrEmpty(drow["AssignedTo"].ToString()))
                        item.Title += " Assigned To:" + drow["AssignedTo"].ToString();
                    else
                        item.Title += " Assigned To:" + AssignedTo;
                    string Description = "";

                    if (!string.IsNullOrEmpty(drow["tfsProjectName"].ToString()))
                        Description += "Project:" + drow["tfsProjectName"].ToString() + "<br />";

                    Description += "Type:" + drow["Type"].ToString() + "<br />";
                    if (!string.IsNullOrEmpty(drow["Description"].ToString()))
                        Description += drow["Description"].ToString();
                    Description += "<br/><b>Assigned by:" + drow["ChangedBy"].ToString() + "</b> at " + ((DateTime)drow["ChangedDate"]).ToString("ddd, dd MMM yyyy HH':'mm':'ss 'GMT'");
                    Description += "<br/><img src=\"";
                    Description += HttpContext.Current.Request.Url.AbsoluteUri.Substring(0, HttpContext.Current.Request.Url.AbsoluteUri.LastIndexOf('/') + 1) + "MarkAsRead.ashx?FeedSID=";
                    Description += drow["SID"].ToString();
                    Description += "\" alt=\"\" style=\"display: block;\" width=\"0\" hieght=\"0\" />";
                    item.Description = Description;
                    uri = new System.Uri(Settings.Default.tfsWorkItemURL + drow["ID"].ToString() + "&rssGuid=" + ((Guid)drow["rssGuid"]).ToString());
                    item.Link = uri;
                    rssGuid = new RssGuid();
                    rssGuid.Name = ((Guid)drow["rssGuid"]).ToString();
                    rssGuid.PermaLink = false;
                    rssSource = new RssSource();
                    rssSource.Name = "TFS";
                    uri = null;
                    rssSource.Url = uri;
                    // item.PubDate = (DateTime)drow["CreatedDate"];
                    item.PubDate = (DateTime)drow["ChangedDate"];
                    //Add Item to channel
                    channel.Items.Add(item);
                }
                if (channel.Items.Count > 0)
                    rssFeed.Channels.Add(channel);
                else rssFeed = null;
            }
            else rssFeed = null;

        }
    }
}